package question2;

import java.io.File;
// import des classes de gestion des fichiers en ecriture
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.ObjectOutputStream;
// import des classes de gestion des fichiers en lecture
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.ObjectInputStream;
// exceptions susceptibles d'etre engendrees lors d'une operation de lecture ou d'ecriture
import java.io.IOException;
import java.io.FileNotFoundException;
// exception liee a la serialisation
import java.lang.ClassCastException;

import java.util.SortedMap;
import java.util.SortedSet;
/* a completer */
/* a completer */
import java.util.Set;

import java.util.Calendar;
import java.util.Locale;
import java.util.Iterator;
import java.util.Date;
import java.util.TreeMap;

import java.text.DateFormat;

// emploi de getResource (voir java.lang.Class)
import java.net.URL;

import org.omg.PortableInterceptor.SUCCESSFUL;

public class FileHandler extends Handler<Float>
{
	private final static int MAX= 5;
	private String fileName;
	private int counter;

	private SortedMap<Date, Float> table;

	public FileHandler( String fileName, Handler<Float> successor )
	{
		/* a completer */

		this.fileName= fileName;
		this.counter= 0;
		table = new TreeMap<Date, Float>();
	} // FileHandler()

	public boolean handleRequest( Float value )
	{
		Calendar c= Calendar.getInstance();		
		table.put(c.getTime(), value);
		counter++;
		if(counter == MAX){
			try {
				writeHTML();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			counter = 0;
		}
		return super.handleRequest(value); /* a modifier */
	} // handleRequest()

	/** Cette methode genere un fichier HTML .
	 */
	private void writeHTML() throws IOException
	{
		BufferedWriter bw= new BufferedWriter( new PrintWriter( new FileWriter(
				fileName + ".html" ) ) );
		bw.write( "<html><head><title>mesures du taux d'humidite relative</title>" );
		bw.write( "<meta http-equiv=\"refresh\" content=\"30\">" );
		bw.write( "</head><body><br>\r\n<table border=\"2\" bgcolor=\"#CBFEEA\">" );

		Set<Date> cles = table.keySet();
		Iterator<Date> it = cles.iterator();
		while (it.hasNext()){
			Date cle = it.next(); 
			Float valeur = table.get(cle);

			DateFormat df= DateFormat.getDateInstance( DateFormat.SHORT, Locale.FRANCE );
			DateFormat dt= DateFormat.getTimeInstance( DateFormat.SHORT, Locale.FRANCE );
			String date= df.format( cle.getTime() ) + "-" + dt.format( cle.getTime() );
			bw.write( "<tr><td>"+date+"</td>\n<td>"+valeur+"</td></tr>");
		}
		bw.write( "</table>\r\n</body></html>" );
		bw.close();
	} // writeHTML()

} // FileHandler
